package com.brossdong.socket.netty.runtime;

import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

/**
 * Created by brossdong on 2018/2/24.
 */
public class ServerHandler extends ChannelHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //请求数据
        Request request = (Request) msg;

        //打印出来
        System.out.println("Server:" + request.getId() + "," + request.getName() + "," + request.getRequestMessage());

        //响应数据
        Response response = new Response();
        response.setId(request.getId());
        response.setName("response:" + request.getName());
        response.setResponseMessage("响应内容:" + request.getRequestMessage());

        //冲刷回去给客户端
        ctx.writeAndFlush(response);//.addListener(ChannelFutureListener.CLOSE)
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
